import {messages} from "share/common";
/**
 * Created by wangjiakun on 2018/6/14 0014.
 */
import React from 'react';
import {connect} from 'react-redux';
import {getApprovelHistory} from 'share/common';
import menuRoute from 'routes/menuRoute';

import {Form, Affix, Button, Card, Select, Radio, Spin, Divider, Row, Col, message, Dropdown, Icon, Menu, Alert, Tooltip} from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
import baseService from 'share/base.service'

import SubsidyRuleService from 'containers/expense-reimbursement-control/expense-standard/subsidy-rule/subsidy-rule-service';
import travelUtil from 'containers/request/travel-request/travelUtil';
import 'styles/expense-reimbursement-control/expense-standard/subsidy-rule/subsidy-rule.scss';

class BaseSubsidy extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      request: false,//是否有与后台交互
      isEdit: false,//是否是在编辑状态
      isCanChange: false,//基础设置是否可修改差补金额
      baseData: {},//基础设置数据
      changeMountTip: '',//员工修改差补金额的基础规则文字展示
      requestList: [],//公司级表单
      listSubsidyRule: menuRoute.getRouteItem('list-subsidy-rule', 'key'),
      copyListSubsidyRule:JSON.parse(JSON.stringify(menuRoute.getRouteItem('list-subsidy-rule', 'key'))),
      setOfBooks: [],
      setOfBooksTravelForms: [],//帐套级表单
      loading: false,
      nowSetOfBooks: {
        id: '',
        setOfBooksName: ''
      }
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.nowSetOfBooks.id !== this.props.nowSetOfBooks.id) {
      this.setState({
        nowSetOfBooks: nextProps.nowSetOfBooks
      }, () => {
        // this.getBaseData();
        this.getSubsidyList();
      })
    }


  };

  componentDidMount() {
    let setOfBooksId = this.props.company.setOfBooksId;
    this.setState({
      listSubsidyRule: this.state.copyListSubsidyRule,
      nowSetOfBooks: this.props.nowSetOfBooks
    }, () => {
      this.getSubsidyList();
    })
    // if (!this.props.tenantMode) {
    //
    // }
    // this.getSubsidyList();
    // if (this.props.tenantMode) {
    //   this.getSubsidyList();
    //   // baseService.getSetOfBooksByTenant().then(resp => {
    //   //   if (resp.status === 200 && resp.data) {
    //   //     let nowSetOfBooks = {};
    //   //     resp.data.map(item => {
    //   //       if(item.id === setOfBooksId)
    //   //         nowSetOfBooks = item;
    //   //     });
    //   //     this.setState({ setOfBooks: resp.data, nowSetOfBooks },  this.getSubsidyList);
    //   //   }
    //   // }).catch(error => {
    //   //   message.error(messages('common.error'));
    //   // });
    // }else {
    //   this.setState({ setOfBooks: [
    //       {id: setOfBooksId}
    //     ] }, this.getSubsidyList)
    // }
  }


  //获取基础规则数据
  getBaseData = () => {
    SubsidyRuleService.getSubsidyBaseAndList({setOfBooksId: this.state.nowSetOfBooks.id}).then(res => {

      this.setState({baseData: res.data, changeMountTip: res.data.content, isCanChange: res.data.isCan});
    }).catch(err => {
      message.error(err.response.data.message);
    })
  }

  //设置员工修改金额初始值
  setSubsidyAmountRule = (data) => {
    let content = ''
    let isCan = true;
    if (data.allowanceAmountModify === 1002) {
      content = `${messages('setting.key1065'/*可修改*/)},${messages('setting.key1066'/*修改后金额不可大于原金额*/)}`;
    } else if (data.allowanceAmountModify === 1003) {
      content = `${messages('setting.key1065'/*可修改*/)},${messages('setting.key1067'/*修改后金额可以大于原金额*/)}`;
    } else {
      content = `${messages('setting.key1068'/*不可修改*/)}`;
      isCan = false;
    }
    return {content: content, isCan: isCan};
  }

  //获取差补申请单列表
  getSubsidyList = () => {
    const {tenantMode} = this.props;
    this.setState({loading: true});
    SubsidyRuleService.getSubsidyBaseAndList({setOfBooksId: tenantMode ? this.state.nowSetOfBooks.id : null}).then(res => {
      if (res.data) {
        let result = this.setSubsidyAmountRule(res.data);
        this.setState({
          changeMountTip: result.content,
          isCanChange: result.isCan,
          baseData: res.data,
          requestList: res.data.companyTravelForms || [],
          setOfBooksTravelForms: res.data.setOfBooksTravelForms || [],
          loading: false
        });
      }
    }).catch(err => {
      this.setState({loading: false});
      message.error(err.response.data.message);
    })
  }

  cfo = travelUtil.createFormOption;

  //基础规则设置保存
  saveBaseSet = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.setState({request: true});
        if (values.allowanceAmountModify === 1002 && values.amount === 1) {
          values.allowanceAmountModify = 1002;
        } else if (values.allowanceAmountModify === 1002 && values.amount === 2) {
          values.allowanceAmountModify = 1003;
        }
        delete values.amount;
        SubsidyRuleService.saveSubsidyBaseData(values, this.props.tenantMode?this.state.nowSetOfBooks.id:'').then(res => {
          this.getSubsidyList();
          this.cancelEdit();
          this.setState({request: false});
          message.success(messages('setting.key1069'/*已保存*/));
        }).catch(err => {
          message.error(err.response.data.message);
        })
      }
    });

  }

  //取消编辑
  cancelEdit = () => {
    let result = this.setSubsidyAmountRule(this.state.baseData);
    this.setState({isEdit: false, isCanChange: result.isCan});
  }

  //编辑
  toEditBase = () => {
    let result = this.setSubsidyAmountRule(this.state.baseData);
    this.setState({isEdit: true, isCanChange: result.isCan}, () => {
      this.props.form.resetFields();
    });
  }

  //基础规则设置修改金额变化的监听
  isCanChangeMount = (e) => {
    let isCan = false;
    isCan = e.target.value === 1001 ? false : true;
    this.setState({isCanChange: isCan});
  }

  /**
   * 页面跳转
   * @param witch 跳转到哪一个页面 list：单据规则列表页面，detail，规则新增，编辑页面
   * @param item  单据概要数据，如formOID
   */
  goTo = (witch, item,type) => {
    if (!item.dimensionInit && !this.props.tenantMode && type === 'tenant') {
      message.info(messages('setting.key1625')/*请联系集团管理员设置规则*/);  //操作成功
      return
    }
    switch (witch) {
      case 'list':
        this.state.listSubsidyRule.url += (!this.props.tenantMode && type === 'tenant') ? '?readonly=true':`?setOfBooksId=${this.state.nowSetOfBooks.id}`;
        this.context.router.push(this.state.listSubsidyRule.url.replace(':formOID', item.formOID));
        break;
      case 'detail':
        break;
    }
  }

  render() {
    const {request, isEdit, baseData, requestList, changeMountTip, isCanChange, setOfBooks, loading, setOfBooksTravelForms} = this.state;
    const {getFieldDecorator} = this.props.form;
    const {tenantMode} = this.props;
    // const menuSetOfBooks = (
    //   <Menu onClick={this.handleChangeSetOfBooks}>
    //     {setOfBooks.map(item => <Menu.Item key={item.id}>{item.setOfBooksName}</Menu.Item>)}
    //   </Menu>
    // );
    return (
      <div className="subsidy-rules">
        <div className="title-edit">
          <h3 className="header-title">{messages('setting.key1070'/*基础设置*/)}</h3>
          <a onClick={this.toEditBase} className="to-edit">{messages('setting.key1071'/*编辑*/)}</a>
        </div>
        {
          isEdit ?
            <Spin spinning={request}>
              <Form>
                <div className="display-flex">
                  <span>{messages('setting.key1072'/*每人每天只能提交一条相同费用类型的差补，超出后将*/)}:</span>
                  <span>&nbsp;&nbsp;&nbsp;{messages('expense-reimbursement-control.key82')/*[申请单差补管控]:*/}</span>
                  <FormItem className="form-item-margin">
                    {getFieldDecorator('allowanceReduplicateTreatment', {
                      initialValue: baseData.allowanceReduplicateTreatment ? baseData.allowanceReduplicateTreatment : 1001
                    })(
                      <Select
                        style={{width:  150}}
                        placeholder={messages("common.please.select")/*请选择*/}
                        getPopupContainer={triggerNode => triggerNode.parentNode}
                      >
                        <Option value={1001}>{messages('setting.key1073'/*警告*/)}</Option>
                        <Option value={1002}>{messages('setting.key1074'/*不可提交*/)}</Option>
                      </Select>
                    )}
                  </FormItem>
                  <span>&nbsp;&nbsp;&nbsp;{messages('expense-reimbursement-control.key83')/*[报销单差补管控]:*/}</span>
                  <FormItem className="form-item-margin">
                    {getFieldDecorator('reimbSubsidyDuplicateValue', {
                      initialValue: baseData.reimbSubsidyDuplicateValue ? baseData.reimbSubsidyDuplicateValue : undefined
                    })(
                      <Select
                        style={{width:  250}}
                        placeholder={messages("common.please.select")/*请选择*/}
                        getPopupContainer={triggerNode => triggerNode.parentNode}
                      >
                        <Option value={1003}>{messages('setting.key1074'/*不可提交*/)}</Option>
                        <Option value={1001}>{messages('expense-reimbursement-control.key84')/*取最后一个目的地当天的补贴金额*/}</Option>
                        <Option value={1002}>{messages('expense-reimbursement-control.key85')/*取城市就高的补贴金额*/}</Option>
                      </Select>
                    )}
                  </FormItem>
                </div>
                <div className="display-flex">
                  <span>{messages('setting.key1075'/*员工是否可修改差补金额*/)}:</span>
                  <FormItem className="form-item-margin">
                    {getFieldDecorator('allowanceAmountModify', this.cfo('', {
                      type: 'number',
                      value: baseData.allowanceAmountModify > 1001 ? 1002 : 1001
                    }, true))(
                      <RadioGroup onChange={this.isCanChangeMount}>
                        <Radio value={1001}>{messages('setting.key1068'/*不可修改*/)}</Radio>
                        <Radio value={1002}>{messages('setting.key1065'/*可修改*/)}</Radio>
                      </RadioGroup>
                    )}
                  </FormItem>
                  {isCanChange &&
                  <FormItem style={{minWidth: 240, maxWidth: 520, marginBottom: 0}}>
                    {
                      getFieldDecorator('amount', this.cfo('', {
                        type: 'number',
                        value: baseData.allowanceAmountModify > 1002 ? 2 : 1
                      }, true))(
                        <Select>
                          <Option value={1}>{messages('setting.key1066'/*修改后金额不可大于原金额*/)}</Option>
                          <Option value={2}>{messages('setting.key1067'/*修改后金额可以大于原金额*/)}</Option>
                        </Select>
                      )
                    }
                  </FormItem>
                  }
                </div>
                <div className="display-flex">
                  <span>{messages('expense-reimbursement-control.key88')/*报销单自动获取补贴方式*/}&nbsp;
                    <Tooltip
                      title={(
                        <div>
                          <div>{messages('expense-reimbursement-control.key89')/*启用[报销单头起止日期生成补贴]，需同时：*/}</div>
                          <div>{messages('expense-reimbursement-control.key90')/*1、报销单选择补贴规则；*/}</div>
                          <div>{messages('expense-reimbursement-control.key91')/*2、补贴规则无[城市]和[值列表]维度。*/}</div>
                        </div>
                      )}
                      placement="bottom"
                    >
                      <Icon type="info-circle-o" />
                    </Tooltip>
                    :
                  </span>
                  <FormItem className={"form-item-margin"}>
                    {getFieldDecorator('allowanceAttachExpenseReportDisable', {
                      initialValue: baseData.hasOwnProperty('allowanceAttachExpenseReportDisable') ? baseData.allowanceAttachExpenseReportDisable : undefined,
                    })(
                      <RadioGroup>
                        <Radio value="true">{messages('expense-reimbursement-control.key92')/*申请单补贴带入*/}</Radio>
                        <Radio value="default">{messages('expense-reimbursement-control.key93')/*报销单头起止日期生成补贴*/}</Radio>
                        <Radio value="false">{messages('expense-reimbursement-control.key94')/*不自动获取*/}</Radio>
                      </RadioGroup>
                    )}
                  </FormItem>
                </div>
                <div className="display-flex">
                  <span> {messages('expense-reimbursement-control.key65')/*自动计算行程*/}&nbsp;
                    <Tooltip title={messages('expense-reimbursement-control.key66')/*启用后，行程上会显示出发城市字段、到达城市字段，到达城市会参与差补计算。只对报销单表单适用*/} placement="bottom">
                      <Icon type="info-circle-o" />
                    </Tooltip>
                    :
                  </span>
                  <FormItem className={"form-item-margin"}>
                    {getFieldDecorator('travelAutoCalculateEnable', {
                      initialValue: !!baseData.travelAutoCalculateEnable,
                    })(
                      <RadioGroup>
                        <Radio value={true}>{messages('setting.key1077'/*是*/)}</Radio>
                        <Radio value={false}>{messages('setting.key1078'/*否*/)}</Radio>
                      </RadioGroup>
                    )}
                  </FormItem>
                </div>
              </Form>
              <div style={{marginTop: 12}}>
                <Button type="primary" loading={request}
                        onClick={this.saveBaseSet}>{messages('setting.key1079'/*保存*/)}</Button>
                <Button style={{marginLeft: 12}} onClick={this.cancelEdit}>{messages('setting.key1080'/*取消*/)}</Button>
              </div>
            </Spin> :
            <Spin spinning={loading}>
              <Row style={{marginBottom: 12}}>
                {messages('setting.key1072'/*每人每天只能提交一条相同费用类型的差补，超出后将*/)}:
                &nbsp;&nbsp;&nbsp;{messages('expense-reimbursement-control.key82')/*[申请单差补管控]:*/}&nbsp;
                {baseData.allowanceReduplicateTreatment === 1001 ? messages('setting.key1073'/*警告*/) : messages('setting.key1074'/*不可提交*/)}
                &nbsp;&nbsp;&nbsp;{messages('expense-reimbursement-control.key83')/*[报销单差补管控]:*/}&nbsp;
                {baseData.reimbSubsidyDuplicateValue === 1001 && (<span>{messages('expense-reimbursement-control.key84')/*取最后一个目的地当天的补贴金额*/}</span>)}
                {baseData.reimbSubsidyDuplicateValue === 1002 && (<span>{messages('expense-reimbursement-control.key85')/*取城市就高的补贴金额*/}</span>)}
                {baseData.reimbSubsidyDuplicateValue === 1003 && (messages('setting.key1074'/*不可提交*/))}
                {!baseData.reimbSubsidyDuplicateValue && (<span>--</span>)}
              </Row>
              <Row style={{marginBottom: 12}}>{messages('setting.key1075'/*员工是否可修改差补金额*/)}:&nbsp;{changeMountTip}</Row>
              <Row style={{marginBottom: 12}}>
                {messages('expense-reimbursement-control.key88')/*报销单自动获取补贴方式*/}&nbsp;
                <Tooltip
                  title={(
                    <div>
                      <div>{messages('expense-reimbursement-control.key89')/*启用[报销单头起止日期生成补贴]，需同时：*/}</div>
                      <div>{messages('expense-reimbursement-control.key90')/*1、报销单选择补贴规则；*/}</div>
                      <div>{messages('expense-reimbursement-control.key91')/*2、补贴规则无[城市]和[值列表]维度。*/}</div>
                    </div>
                  )}
                  placement="bottom"
                >
                  <Icon type="info-circle-o" />
                </Tooltip>
                :&nbsp;
                {(baseData.hasOwnProperty('allowanceAttachExpenseReportDisable') && !!baseData.allowanceAttachExpenseReportDisable) ? (<span>
                  {baseData.allowanceAttachExpenseReportDisable === 'true' && (messages('expense-reimbursement-control.key92')/*申请单补贴带入*/)}
                  {baseData.allowanceAttachExpenseReportDisable === 'default' && (messages('expense-reimbursement-control.key93')/*报销单头起止日期生成补贴*/)}
                  {baseData.allowanceAttachExpenseReportDisable === 'false' && (messages('expense-reimbursement-control.key94')/*不自动获取*/)}
                </span>) : '--'}
              </Row>
              <Row style={{marginBottom: 12}}> {messages('expense-reimbursement-control.key65')/*自动计算行程*/}&nbsp;
                <Tooltip title={messages('expense-reimbursement-control.key66')/*启用后，行程上会显示出发城市字段、到达城市字段，到达城市会参与差补计算。只对报销单表单适用*/} placement="bottom">
                  <Icon type="info-circle-o" />
                </Tooltip>
                :&nbsp;
                {baseData.travelAutoCalculateEnable ? messages('setting.key1077'/*是*/) : messages('setting.key1078'/*否*/)}
              </Row>
            </Spin>
        }
        <Divider></Divider>
        {tenantMode && <Alert style={{marginBottom:'12px'}} message={messages('setting.key1626')/*注：帐套级单据差补规则，将根据表单分配情况，分配给相应的公司*/} type="info" showIcon/>}
        {tenantMode && <h3 className="header-title" style={{marginBottom:'12px'}}>{messages('setting.key1081'/*单据差补规则设置*/)}</h3>}
        {tenantMode && setOfBooksTravelForms.length === 0 && <div>{messages('setting.key1627')/*该帐套下没有表单*/}</div>}
        {loading ? <Spin/> : (
            <div>
              {!tenantMode && <h3 className="header-title">{messages('setting.key1628')/*公司级单据-差补规则设置*/}</h3>}
              {!tenantMode && requestList.length === 0 && <div>{messages('setting.key1629')/*该公司下没有表单*/}</div>}
              <div className="card-box">
                {!!requestList.length && requestList.map(item => {
                  return (
                    <div className="subsidy-card"
                         onClick={() => this.goTo('list', item,'company')}
                         key={item.formOID}>
                      <h3 className="card-title">{item.formName}</h3>
                      <div className="padding">
                        {
                          item.dimensionInit ? <div>
                              <span>{messages('setting.key1082'/*规则*/)}<span
                                className='default-color-font'>&nbsp;{item.totalRuleNumber}&nbsp;</span>{messages('setting.key1083'/*条*/)}</span>，
                              <span>{messages('setting.key1084'/*启用中*/)}<span
                                className='default-color-font'>&nbsp;{item.enableRuleNumber}&nbsp;</span>{messages('setting.key1083'/*条*/)}</span>
                            </div> :
                            <span>{messages('setting.key1085'/*未设置规则*/)}</span>
                        }
                      </div>
                      <div className="card-divider"></div>
                      <p
                        className={item.formEnable ? 'padding-start' : 'padding-stop'}>{item.formEnable ? messages('setting.key1086'/*启用*/) : messages('setting.key1087'/*禁用*/)}</p>
                    </div>
                  )
                })}
              </div>
              {!tenantMode &&!!setOfBooksTravelForms.length&& <h3 className="header-title">{messages('setting.key1630')/*租户级单据-差补规则设置*/}</h3>}
              <div className="card-box">
                {!!setOfBooksTravelForms.length && setOfBooksTravelForms.map(item => {
                  return (
                    <div className="subsidy-card"
                         onClick={() => this.goTo('list', item,tenantMode?'':'tenant')}
                         key={item.formOID}>
                      <h3 className="card-title">{item.formName}</h3>
                      <div className="padding">
                        {
                          item.dimensionInit ? <div>
                              <span>{messages('setting.key1082'/*规则*/)}<span
                                className='default-color-font'>&nbsp;{item.totalRuleNumber}&nbsp;</span>{messages('setting.key1083'/*条*/)}</span>，
                              <span>{messages('setting.key1084'/*启用中*/)}<span
                                className='default-color-font'>&nbsp;{item.enableRuleNumber}&nbsp;</span>{messages('setting.key1083'/*条*/)}</span>
                            </div> :
                            <span>{messages('setting.key1085'/*未设置规则*/)}</span>
                        }
                      </div>
                      <div className="card-divider"></div>
                      <p
                        className={item.formEnable ? 'padding-start' : 'padding-stop'}>{item.formEnable ? messages('setting.key1086'/*启用*/) : messages('setting.key1087'/*禁用*/)}</p>
                    </div>
                  )
                })}
              </div>
            </div>
          ) }
        <br/><br/>
      </div>)
  }

}
BaseSubsidy.propTypes = {
  nowSetOfBooks: React.PropTypes.object,
};

BaseSubsidy.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    language: state.main.language,
    company: state.login.company,
    tenantMode: state.main.tenantMode
  };
}

const wrappedBasesSubsidy = Form.create()(BaseSubsidy);

export default connect(mapStateToProps)(wrappedBasesSubsidy);


